var form,$,table,layer,upload,node;
var user = JSON.parse(localStorage.getItem("user"));
var userId = user.userId;
layui.use(['form','jquery','table','layer','upload'],function() {
    form = layui.form;
    $ = layui.jquery;
    table = layui.table;
    layer = layui.layer;
    upload = layui.upload;

    //获取微圈分类树数据
    getJsActicleCategroy();
    //获取微圈列表数据
    getMicrocircleList('','','','');

    //table点击事件，存储数据
    table.on('row(test)',function (data) {
        localStorage.setItem("microCircleData",JSON.stringify(data.data));
    });
});

//获取微圈分类树数据
function getJsActicleCategroy(){
    $.ajax({
        url: "/microcircle/getJsActicleCategroy",
        type: "post",
        dataType: "json",
        data: {},
        success: function (item) {
            //展示分类树
            showJsActicleCategroyZtree(item.data);
        }
    });
}

//展示微圈分类树
function showJsActicleCategroyZtree(data){
    //Ztree配置
    var setting = {
        data:{
            simpleData: {
                enable: true,
                idKey: "acticleCategroyId",
                pIdKey: "parentId",
                rootPId: -1,
            },
            key: {
                name: "artcleCategroyName"
            }
        },
        check: {
            enable: true,
            chkStyle: "checkbox",
        },
        view:{
            showLine: true,
            showIcon:false,
            //添加树节点长度限制
            addDiyDom: addDiyDom
        },
        callback:{
            onClick: showTable, //点击事件回调
            onRightClick: onRightClick, //鼠标右键回调
            //点击前回调
            beforeCheck : function zTreeBeforeClick(treeId, treeNode, clickFlag) {
                var zTree = $.fn.zTree.getZTreeObj("treeDemo");
                zTree.checkAllNodes(false);
                return !treeNode.isParent;//当是父节点 返回false 不让选取
            },
            onCheck: choose,//点击回调
        }
    };
    //点击对应树节点展示微圈列表
    function choose(event,treeId,treeNode){
        getMicrocircleList('','','',treeNode.acticleCategroyId);
    }
    //添加树节点数据长度限制
    function addDiyDom(treeId, treeNode) {
        var spaceWidth = 5;
        var switchObj = $("#" + treeNode.tId + "_switch"),
            icoObj = $("#" + treeNode.tId + "_ico");
        switchObj.remove();
        icoObj.parent().before(switchObj);
        var spantxt = $("#" + treeNode.tId + "_span").html();
        if (spantxt.length > 6) {
            spantxt = spantxt.substring(0, 6) + "...";
            $("#" + treeNode.tId + "_span").html(spantxt);
        }
    }
    //点击对应树节点展示微圈列表
    function showTable(event,treeId,treeNode){
        //getMicrocircleList('','','',treeNode.acticleCategroyId);
    }
    //右键展示菜单
    function onRightClick(event,treeId,treeNode) {
        node = treeNode;
        if (event.target.tagName.toLowerCase() == "span") {
            var top = event.clientY;
            var left = event.clientX;
            top -= 190;
            left -= 5;
            //定位
            $("#rMenu").css('position','absolute');
            $("#rMenu").css('top',top);
            $("#rMenu").css('left',left);
            $("#rMenu").css("display","inline");
            //隐藏菜单
            $("html").bind("mousedown", onBodyMouseDown);
        }
    }
    //点击隐藏菜单
    function onBodyMouseDown(event){
        if (!($(event.target).parents().is("#rMenu"))) {
            $("#rMenu").css("display","none");
        }
    }
    //初始化ztree
    zTreeObj = $.fn.zTree.init($("#treeDemo"), setting, data);
    zTreeObj.expandAll(true);//展开全部节点
}

//添加ztree树节点
function addZtree() {
    $("#rMenu").css("display","none");
    layer.prompt({
        formType: 0,//0文本
        value: "",
        title: "添加分类",
        area: ['500px', '30px'],
    },function (value,index,elem) {
        $.ajax({
            url: "/microcircle/addZtree",
            type: "post",
            dataType: "json",
            data: {
                "artcleCategroyName":value,
                "createId":userId,
                "parentId":node.acticleCategroyId
            },
            success: function (item) {
                if (item.data){
                    //重新加载树
                    getJsActicleCategroy();
                    layer.msg("添加成功");
                }else{
                    layer.msg("添加失败");
                }
            }
        });
        //关闭弹窗
        layer.close(index);
    });
}

//删除树节点
function delZtree() {
    layer.open({
        type: 1,
        title: "删除节点",
        content: "<div style='font-size: 16px; margin:30px  ;'>您确定要删除此节点吗?</div>",
        area:['300px','200px'],
        btn: ['确定','取消'],
        yes: function (index, layero) {
            if (node.isParent){
                layer.msg("请从子目录开始删除");
                return false;
            }
            $.ajax({
                url: "/microcircle/delZtree",
                type: "post",
                dataType: "json",
                data: {"acticleCategroyId":node.acticleCategroyId},
                success: function (data) {
                    if (data.data) {
                        getJsActicleCategroy();
                        layer.msg("删除成功");
                        $("#rMenu").css("display","none");
                        layer.close(index);
                    }else{
                        layer.msg("删除失败");
                        return false;
                    }
                }
            });
        }
    });
}

//修改树节点
function updateZtree() {
    $("#rMenu").css("display","none");
    layer.prompt({
        formType: 0,
        value: node.artcleCategroyName,
        title: "修改分类",
        area: ['500px', '30px'],
    },function (value,index,elem) {
        $.ajax({
            url: "/microcircle/updateZtree",
            type: "post",
            dataType: "json",
            data: {"artcleCategroyName":value,"acticleCategroyId":node.acticleCategroyId},
            success: function (data) {
                if (data.data) {
                    getJsActicleCategroy();
                    layer.msg("修改成功");
                }else{
                    layer.msg("修改失败");
                }
            }
        });
        layer.close(index);
    });
}

////获取微圈列表信息
function getMicrocircleList(artcleTitle,account,trueName,acticleCategroyId){
    $.ajax({
        url:'/microcircle/getMyMicrocircleList',
        type: "post",
        dataType:'json',
        data: {
            "artcleTitle": artcleTitle,
            "account": account,
            "trueName": trueName,
            "acticleCategroyId":acticleCategroyId
        },
        success:function (data) {
            //展示table表格
            showMicrocircleList(data.data);
        }
    });
}

function showMicrocircleList(data) {
    table.render({
        elem: "#demo",
        data: data,
        page: true,
        limit: 10,
        cols: [[
            {checkbox:true},
            {field:'microcircleId',title:'序号',align:'center',height:'20px',unresize:true},
            {field:'trueName',title:'用户昵称',align:'center',unresize:true},
            {field:'artcleTitle',title:'文章标题',align:'center',unresize:true},
            {field:'createDate',title:'创建时间',width:170,align:'center',unresize:true},
            {field:'account',title:'用户账号',align:'center',unresize:true},
            {field:'acticleLike',title:'点赞数量',align:'center',unresize:true},
            {field:'collectionNum',title:'收藏数量',align:'center',unresize:true,templet:function (data) {
                    var collectionNum = 0
                    $.ajax({
                        url:'/microcircle/getMyMicrocircleCollectionNums',
                        type: "post",
                        dataType:'json',
                        async: false,
                        data: {"microcircleId": data.microcircleId },
                        success:function (data) {
                            if (data.data != null){
                                collectionNum = data.data;
                            } else{
                                collectionNum = 0;
                            }
                        }
                    });
                    localStorage.setItem("collectionNum",collectionNum);
                    return collectionNum;
                }},
            {field:'acticleReviews',title:'评论数量',align:'center',unresize:true},
            {field:'acticleShare',title:'分享数量',align:'center',unresize:true},
            {field:'',title:'操作',align:'center',width:100,unresize:true,templet:function(data){
                    return "<a class='operation' onclick='seeMicroCircle("+data.microcircleId+")'>查看</a>&nbsp&nbsp"+
                        "<a onclick='delMyMicroCircle(\""+data.microcircleId+"\")' class='operation'>删除</a>";
                }},
        ]]
    });
}

//删除
function delMyMicroCircle(microcircleId) {
    layer.open({
        type: 1,
        title: "删除微圈",
        content: "<div style='font-size: 16px; margin:30px  ;'>您确定要删除此微圈吗?</div>",
        area:['300px','200px'],
        btn: ['确定','取消'],
        yes: function (index, layero) {
            $.ajax({
                url: "/microcircle/delMicroCircle",
                dataType: "json",
                type: "post",
                data: {"microcircleId":microcircleId},
                success: function (data) {
                    getMicrocircleList('','','','');
                    addLog(3,3,'删除微圈');//3：微圈 3：删除
                    layer.msg("删除成功");
                    layer.close(index);
                }
            });
        }
    });
}

//查看
function seeMicroCircle(microcircleId) {
    layer.open({
        type: 2,
        title: "管理微圈",
        area: ['1000px','550px'],
        content: "/microCircle/seeMicroCircle.html",
        success: function (layero,index) {
            var microCircleData = JSON.parse(localStorage.getItem("microCircleData"));
            console.log(microCircleData);
            var objData = layero.find("iframe").contents();
            addLog(3,5,'查看微圈');//3：微圈 5：查找
            //头像
            objData.find("#headerImage").attr("src",microCircleData.acatarUrl);
            //标题
            objData.find("#span_title").text(microCircleData.artcleTitle);
            //昵称
            objData.find("#p_name").text(microCircleData.trueName);
            //标题（右）
            objData.find("#titleid").text(microCircleData.artcleTitle);
            //创作人
            objData.find("#span_user").text(microCircleData.trueName);
            //日期
            objData.find("#span_date").text(microCircleData.releaseDate);
            //分类
            queryMicroCircleClass(objData,microCircleData.acticleCategroyId);
            //账号
            objData.find("#span_id").text(microCircleData.account);
            //内容
            objData.find("#text_id").html(microCircleData.article);
            //用户名
            objData.find("input[name=userName]").val(user.trueName);
            //账号
            objData.find("input[name=userNum]").val(user.account);
        }
    });
}

//查询分类
function queryMicroCircleClass(objData,acticleCategroyId) {
    $.ajax({
        url: "/microcircle/queryMicroCircleClass",
        type: "post",
        dataType: "json",
        data: {"acticleCategroyId": acticleCategroyId},
        success: function (item) {
            if (item.data != null){
                objData.find("#span_fenlei").text(item.data.artcleCategroyName);
            }
        }
    });
}

//搜索
$("#selMicroCircle").on("click",function () {
    var artcleTitle = $("input[name=artcleTitle]").val();
    var account = $("input[name=account]").val();
    var trueName = $("input[name=trueName]").val();
    getMicrocircleList(artcleTitle,account,trueName,'');
});

//刷新
function refresh() {
    location.reload();
}

//返回首页
function backOff(){
    parent.jumpSystemHome();
}

//添加操作日志
function addLog(logType,type,remark) {
    $.ajax({
        url: "/microcircle/addLog",
        dataType: "json",
        type: "post",
        data: {"logType":logType,"type":type,"userId":userId,"remark":remark},
        success: function (data) {

        }
    });
}